﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
    ViewData["Title"] = "修改物料入库单";
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>修改物料入库单</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" media="all">
    <style>
        body {
            background-color: #f5f7fa;
            font-family: 'Microsoft YaHei', 'PingFang SC', Arial, sans-serif;
            margin: 0;
            padding: 20px 0;
        }
        .form-container {
            max-width: 1200px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }
        .form-header {
            background: linear-gradient(135deg, #ff7a00 0%, #ff9500 100%);
            color: white;
            padding: 25px 40px;
            text-align: center;
        }
        .form-title {
            font-size: 20px;
            font-weight: 500;
            margin: 0;
        }
        .form-body {
            padding: 40px;
        }
        .layui-form-item {
            margin-bottom: 28px;
        }
        .form-row {
            display: flex;
            gap: 30px;
            margin-bottom: 28px;
        }
        .form-col {
            flex: 1;
        }
        .layui-form-label {
            width: 140px;
            padding: 0;
            color: #2d3748;
            font-weight: 500;
            background: none;
            border: none;
            text-align: right;
            line-height: 44px;
            float: left;
        }
        .layui-input-block {
            margin-left: 160px;
        }
        .layui-input, .layui-select, .layui-textarea {
            height: 44px;
            line-height: 44px;
            padding: 0 15px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.2s ease;
            background: #fff;
        }
        .layui-input:focus, .layui-select:focus, .layui-textarea:focus {
            border-color: #ff7a00;
            box-shadow: 0 0 0 3px rgba(255, 122, 0, 0.1);
            outline: none;
        }
        .layui-textarea {
            height: auto;
            line-height: 1.5;
            padding: 12px 15px;
            min-height: 80px;
            resize: vertical;
        }
        .auto-generate-wrapper {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .auto-generate-wrapper .layui-input {
            flex: 1;
            min-width: 300px;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 13px;
        }
        .switch-btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 15px;
            background: #f7fafc;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            font-size: 12px;
            color: #4a5568;
            cursor: pointer;
            transition: all 0.2s ease;
            white-space: nowrap;
            flex-shrink: 0;
        }
        .switch-btn:hover {
            background: #edf2f7;
            border-color: #cbd5e0;
        }
        .supplier-wrapper {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .supplier-wrapper .layui-input {
            flex: 1;
        }
        .supplier-select-btn {
            width: 44px;
            height: 44px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            background: #fff;
            color: #ff7a00;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            flex-shrink: 0;
        }
        .supplier-select-btn:hover {
            background: #ff7a00;
            color: white;
            border-color: #ff7a00;
        }
        .required-mark {
            color: #e53e3e;
            margin-right: 4px;
        }
        .form-actions {
            padding: 30px 40px;
            background: #f7fafc;
            text-align: center;
            border-top: 1px solid #e2e8f0;
        }
        .layui-btn {
            height: 44px;
            line-height: 44px;
            padding: 0 32px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        .btn-primary {
            background: linear-gradient(135deg, #ff7a00 0%, #ff9500 100%);
            color: white;
            margin-right: 12px;
        }
        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(255, 122, 0, 0.3);
        }
        .btn-default {
            background: #fff;
            color: #4a5568;
            border: 1px solid #e2e8f0;
        }
        .btn-default:hover {
            background: #f7fafc;
            border-color: #cbd5e0;
        }
        .layui-input.disabled {
            background: #f7fafc;
            color: #a0aec0;
            cursor: not-allowed;
        }
        .layui-input[readonly] {
            background: #f7fafc;
            color: #a0aec0;
            cursor: not-allowed;
        }
        .layui-form-item::after {
            content: "";
            display: block;
            clear: both;
        }
        
        /* 响应式设计 */
        @@media (max-width: 768px) {
            body {
                padding: 10px;
            }
            .form-header, .form-body, .form-actions {
                padding: 20px;
            }
            .form-row {
                flex-direction: column;
                gap: 0;
            }
            .layui-input-block {
                margin-left: 0;
            }
            .layui-form-label {
                width: auto;
                text-align: left;
                float: none;
                line-height: normal;
                margin-bottom: 8px;
            }
            .auto-generate-wrapper {
                flex-direction: column;
                align-items: stretch;
            }
            .switch-btn {
                align-self: flex-start;
                margin-top: 10px;
            }
        }
        /* 弹窗美化样式 */
        .modal-card {
            background: #fff;
            border-radius: 14px;
            box-shadow: 0 4px 24px rgba(80, 120, 200, 0.10);
            padding: 28px 36px 18px 36px;
            margin: 0 auto;
            max-width: 900px;
        }
        .modal-title {
            font-size: 22px;
            font-weight: 600;
            color: #3a3a3a;
            margin-bottom: 18px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .modal-title i {
            color: #ff7a00;
            font-size: 22px;
        }
        .modal-form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 22px 32px;
            align-items: center;
        }
        .modal-form-group {
            display: flex;
            flex-direction: column;
        }
        .modal-form-group {
            grid-column: 1 / -1;
        }
        .modal-label {
            font-weight: 500;
            color: #333;
            margin-bottom: 6px;
            font-size: 15px;
            display: flex;
            align-items: center;
        }
        .modal-required {
            color: #f56c6c;
            margin-right: 4px;
            font-size: 15px;
        }
        .modal-input, .modal-textarea, .modal-form-group select {
            border: 1px solid #e0e3ea;
            border-radius: 6px;
            padding: 7px 12px;
            font-size: 15px;
            transition: border 0.2s;
            background: #fafbff;
            height: 38px;
        }
        .modal-input:focus, .modal-textarea:focus, .modal-form-group select:focus {
            border: 1.5px solid #ff7a00;
            background: #fff;
            outline: none;
        }
        .modal-textarea {
            min-height: 60px;
            resize: vertical;
        }
        .modal-qty-group {
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .modal-qty-btn {
            width: 28px;
            height: 28px;
            border-radius: 4px;
            border: 1px solid #e0e3ea;
            background: #f3f4f8;
            color: #ff7a00;
            font-size: 18px;
            cursor: pointer;
            transition: background 0.2s, border 0.2s;
        }
        .modal-qty-btn:hover {
            background: #e0e3ea;
            border: 1.5px solid #ff7a00;
        }
        /* 添加弹窗底部按钮样式 */
        .modal-btns {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 24px;
            padding-top: 20px;
            border-top: 1px solid #e0e3ea;
        }
        .modal-btn-primary {
            background: #ff7a00;
            color: white;
            border: none;
            padding: 8px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
        }
        .modal-btn-primary:hover {
            background: #ff8c1a;
            transform: translateY(-1px);
        }
        .modal-btn-cancel {
            background: #f3f4f8;
            color: #666;
            border: 1px solid #e0e3ea;
            padding: 8px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
        }
        .modal-btn-cancel:hover {
            background: #e9eaef;
        }
        @@media (max-width: 768px) {
            .modal-card {
                padding: 10px 5px 10px 5px;
                max-width: 100vw;
            }
            .modal-form-grid {
                grid-template-columns: 1fr;
                gap: 12px 0;
            }
        }
    </style>
</head>
<body>
    <div class="form-container">
        <div class="form-header">
            <h1 class="form-title">修改物料入库单</h1>
        </div>
        <div class="form-body">
            <form class="layui-form" lay-filter="procurementForm">
                @Html.AntiForgeryToken()
                <input type="hidden" name="Id" id="procurementId" value="">
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>入库单编号</label>
                            <div class="layui-input-block">
                                <div class="auto-generate-wrapper">
                                    <input type="text" name="LnboundCode" placeholder="请输入入库单编号" autocomplete="off" class="layui-input" id="lnboundCodeInput">
                                    <div class="switch-btn">
                                        <input type="checkbox" name="AutoGenerate" title="自动生成" lay-skin="switch" lay-filter="autoGenerateCode">
                                        <span>自动生成</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>入库单名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="LnboundName" placeholder="请输入入库单名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>入库日期</label>
                            <div class="layui-input-block">
                                <input type="text" name="LnboundDate" id="lnboundDate" placeholder="请选择入库日期" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>采购订单号</label>
                            <div class="layui-input-block">
                                <input type="text" name="ProcurementNumber" id="procurementNumber" placeholder="请输入采购订单号" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>供应商</label>
                            <div class="layui-input-block">
                                <div class="supplier-wrapper">
                                    <input type="text" name="Vendor" placeholder="请选择供应商" autocomplete="off" class="layui-input" readonly>
                                    <input type="hidden" name="SupplierId" id="supplierId">
                                    <button type="button" class="supplier-select-btn" id="selectSupplierBtn">
                                        <i class="layui-icon layui-icon-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>入库仓库</label>
                            <div class="layui-input-block">
                                <select name="LnboundWarehouse" lay-search="">
                                    <option value="">请选择入库仓库</option>
                                    <option value="原料仓库">原料仓库</option>
                                    <option value="成品仓库">成品仓库</option>
                                    <option value="半成品仓库">半成品仓库</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>单据状态</label>
                            <div class="layui-input-block">
                                <select name="DocumentStatus">
                                    <option value="">请选择单据状态</option>
                                    <option value="0">草稿</option>
                                    <option value="1">已完成</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>总金额</label>
                            <div class="layui-input-block">
                                <input type="text" name="TotalAmount" placeholder="请输入总金额" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label"><span class="required-mark">*</span>备注</label>
                    <div class="layui-input-block">
                        <textarea name="Pemark" placeholder="请输入备注内容" class="layui-textarea"></textarea>
                    </div>
                </div>
            </form>
        </div>
        <div class="form-actions">
            <button class="layui-btn btn-primary" lay-submit lay-filter="procurementSubmit">
                <i class="layui-icon layui-icon-ok"></i> 确定修改
            </button>
            <button type="button" class="layui-btn btn-default" id="cancelBtn">
                <i class="layui-icon layui-icon-return"></i> 取消返回
            </button>
        </div>
    </div>

    <!-- 物料信息区域 -->
    <div class="content-card" style="margin-top: 24px;">
        <div class="toolbar" style="margin-bottom: 12px;">
            <button class="layui-btn layui-btn-primary" id="btnAddMaterialDetail"><i class="layui-icon layui-icon-add-1"></i> 新增</button>
            <button class="layui-btn layui-btn-danger" id="btnDeleteMaterialDetail"><i class="layui-icon layui-icon-delete"></i> 删除</button>
        </div>
        <table id="materialDetailsTable" lay-filter="materialDetailsTable"></table>
    </div>

    <!-- 明细操作列模板 -->
    <script type="text/html" id="materialDetailOperationBar">
        <div style="display: flex; flex-direction: column; align-items: center; gap: 2px;">
            <a lay-event="edit" style="color:#409EFF;font-size:13px;line-height:16px;cursor:pointer;">
                <i class="layui-icon layui-icon-edit"></i> 修改
            </a>
            <a lay-event="delete" style="color:#F56C6C;font-size:13px;line-height:16px;cursor:pointer;">
                <i class="layui-icon layui-icon-delete"></i> 删除
            </a>
        </div>
    </script>

    <!-- 新增/编辑物料明细弹窗模板 -->
    <script type="text/html" id="addMaterialDetailDialog">
        <div class="modal-card">
            <div class="modal-title">
                <i class="layui-icon layui-icon-add-1"></i> <span id="materialDetailDialogTitle"></span>
            </div>
            <form class="layui-form" lay-filter="addMaterialDetailForm" autocomplete="off">
                <div class="modal-form-grid">
                    <div class="modal-form-group">
                        <label class="modal-label">* 物料编码</label>
                        <div style="display:flex;align-items:center;gap:6px;">
                            <input type="text" name="MaterialCode" placeholder="请选择物料编码" autocomplete="off" class="modal-input" id="selectMaterialCodeInput" readonly required>
                            <button type="button" class="layui-btn layui-btn-primary layui-btn-xs" id="btnSelectMaterial"><i class="layui-icon layui-icon-search"></i></button>
                        </div>
                    </div>
                    <div class="modal-form-group">
                        <label class="modal-label">物料名称</label>
                        <input type="text" name="MaterialName" autocomplete="off" class="modal-input" id="selectMaterialNameInput" readonly>
                    </div>
                    <div class="modal-form-group">
                        <label class="modal-label">单位</label>
                        <input type="text" name="Unit" autocomplete="off" class="modal-input">
                    </div>
                    <div class="modal-form-group">
                        <label class="modal-label">* 入库数量</label>
                        <div class="modal-qty-group">
                            <button type="button" class="modal-qty-btn" id="btnMinusQty">-</button>
                            <input type="number" name="Quantity" value="0" min="0" class="modal-input" style="width:80px;text-align:center;" required>
                            <button type="button" class="modal-qty-btn" id="btnAddQty">+</button>
                        </div>
                    </div>
                    <div class="modal-form-group">
                        <label class="modal-label">* 单据金额</label>
                        <div class="modal-qty-group">
                            <button type="button" class="modal-qty-btn" id="btnMinusAmount">-</button>
                            <input type="number" name="Amount" value="0" min="0" class="modal-input" style="width:80px;text-align:center;" required>
                            <button type="button" class="modal-qty-btn" id="btnAddAmount">+</button>
                        </div>
                    </div>
                    <div class="modal-form-group">
                        <label class="modal-label">* 入库仓库</label>
                        <select name="Warehouse" id="warehouseSelect" class="modal-input" required>
                            <option value="">请选择</option>
                            <option value="WH001">原料仓库</option>
                            <option value="WH002">成品仓库</option>
                            <option value="WH003">半成品仓库</option>
                        </select>
                    </div>
                    <div class="modal-form-group">
                        <label class="modal-label">规格型号</label>
                        <input type="text" name="Specification" autocomplete="off" class="modal-input">
                    </div>
                    <div class="modal-form-group">
                        <label class="modal-label">入库批次号</label>
                        <input type="text" name="BatchNo" autocomplete="off" class="modal-input">
                    </div>
                    <div class="modal-form-group">
                        <label class="modal-label">有效期</label>
                        <input type="text" name="ValidDate" id="validDateInput" autocomplete="off" class="modal-input">
                    </div>
                    <div class="modal-form-group">
                        <label class="modal-label">是否检验</label>
                        <div style="display:flex;align-items:center;gap:10px;">
                            <input type="radio" name="IsCheck" value="1" title="是">
                            <input type="radio" name="IsCheck" value="0" title="否" checked>
                        </div>
                    </div>
                    <div class="modal-form-group" style="grid-column: 1 / -1;">
                        <label class="modal-label">备注</label>
                        <textarea name="Remark" placeholder="请输入内容" class="modal-textarea"></textarea>
                    </div>
                </div>
                <div class="modal-btns">
                    <button type="button" class="modal-btn-cancel" onclick="layer.closeAll();">取消</button>
                    <button class="modal-btn-primary" lay-submit lay-filter="addOrEditMaterialDetail">保存</button>
                </div>
            </form>
        </div>
    </script>

    <!-- 物料选择弹窗模板 -->
    <script type="text/html" id="materialSelectDialog">
        <div style="padding:20px;">
            <form class="layui-form" id="materialSearchForm" style="margin-bottom:10px;">
                <input type="text" name="materielCode" placeholder="物料编码" class="layui-input" style="width:150px;display:inline-block;">
                <input type="text" name="materielName" placeholder="物料名称" class="layui-input" style="width:150px;display:inline-block;">
                <button class="layui-btn" lay-submit lay-filter="materialSearch">搜索</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </form>
            <table class="layui-hide" id="materialTable" lay-filter="materialTable"></table>
            <div style="text-align:right;margin-top:10px;">
                <button class="layui-btn" id="materialSelectOk">确定</button>
                <button class="layui-btn layui-btn-primary" onclick="layer.closeAll();">取消</button>
            </div>
        </div>
    </script>

    <script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
    layui.use(['form', 'layer', 'laydate', 'table'], function () {
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;
        var table = layui.table;
        var $ = layui.$;

        // 初始化日期选择器
        laydate.render({
            elem: '#lnboundDate',
            type: 'date'
        });

        // 雪花ID生成函数
        function generateSnowflakeId() {
            // 简单雪花算法实现（仅前端，实际可用后端生成）
            var timestamp = Date.now();
            var random = Math.floor(Math.random() * 1000);
            return timestamp.toString() + random.toString().padStart(3, '0');
        }

        // 从URL参数获取采购入库ID
        function getUrlParameter(name) {
            var urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }
        
        var procurementId = getUrlParameter('id');
        
        // 如果有ID，则加载数据进行回显
        if (procurementId && procurementId !== '') {
            $('#procurementId').val(procurementId);
            loadProcurementData(procurementId);
        }

        // 自动生成开关事件
        form.on('switch(autoGenerateCode)', function(data){
            var $input = $('#lnboundCodeInput');
            
            if(data.elem.checked){
                // 生成雪花ID
                var snowflakeId = generateSnowflakeId();
                $input.val(snowflakeId);
                $input.prop('readonly', true);
                $input.addClass('disabled');
                
                // 显示生成成功提示
                layer.msg('已自动生成编号: ' + snowflakeId, {
                    icon: 1,
                    time: 2000
                });
            } else {
                $input.prop('readonly', false);
                $input.removeClass('disabled');
            }
        });

        // 前端表单验证函数
        function validateForm(formData) {
            // 入库单编号验证 - 从输入框直接获取值
            var lnboundCode = $('#lnboundCodeInput').val();
            if (!lnboundCode || lnboundCode.trim() === '') {
                layer.msg('请输入入库单编号', {icon: 2});
                return false;
            }
            // 确保formData中有正确的值
            formData.LnboundCode = lnboundCode;
            
            // 入库单名称验证
            if (!formData.LnboundName || formData.LnboundName.trim() === '') {
                layer.msg('请输入入库单名称', {icon: 2});
                return false;
            }
            
            // 入库日期验证
            if (!formData.LnboundDate || formData.LnboundDate.trim() === '') {
                layer.msg('请选择入库日期', {icon: 2});
                return false;
            }
            
            // 采购订单号验证
            if (!formData.ProcurementNumber || formData.ProcurementNumber.trim() === '') {
                layer.msg('请输入采购订单号', {icon: 2});
                return false;
            }
            
            // 供应商验证
            if (!formData.Vendor || formData.Vendor.trim() === '') {
                layer.msg('请选择供应商', {icon: 2});
                return false;
            }
            
            // 入库仓库验证
            if (!formData.LnboundWarehouse || formData.LnboundWarehouse.trim() === '') {
                layer.msg('请选择入库仓库', {icon: 2});
                return false;
            }
            
            // 单据状态验证
            if (formData.DocumentStatus === undefined || formData.DocumentStatus === null || formData.DocumentStatus === '') {
                layer.msg('请选择单据状态', {icon: 2});
                return false;
            }
            
            // 总金额验证（必填且必须是有效数字）
            if (!formData.TotalAmount || formData.TotalAmount.trim() === '') {
                layer.msg('请输入总金额', {icon: 2});
                return false;
            }
            var amount = parseFloat(formData.TotalAmount);
            if (isNaN(amount) || amount < 0) {
                layer.msg('请输入有效的总金额', {icon: 2});
                return false;
            }
            
            // 备注验证（必填）
            if (!formData.Pemark || formData.Pemark.trim() === '') {
                layer.msg('请输入备注内容', {icon: 2});
                return false;
            }
            
            return true;
        }

        // 加载采购入库数据
        function loadProcurementData(id) {
            var loading = layer.load(2, {
                content: '正在加载数据...',
                time: 10*1000
            });
            
            $.ajax({
                url: '/WarehouseManagement/GetProcurementById',
                type: 'GET',
                data: { id: id },
                success: function(result) {
                    layer.close(loading);
                    if (result.success && result.data) {
                        var data = result.data;
                        
                        // 使用LayUI的form.val方法设置表单值
                        form.val('procurementForm', {
                            "LnboundCode": data.lnboundCode,
                            "LnboundName": data.lnboundName,
                            "ProcurementNumber": data.procurementNumber,
                            "Vendor": data.vendor,
                            "LnboundWarehouse": data.lnboundWarehouse,
                            "DocumentStatus": data.documentStatus.toString(),
                            "TotalAmount": data.totalAmount,
                            "Pemark": data.pemark
                        });
                        
                        // 设置日期
                        if (data.lnboundDate) {
                            var date = new Date(data.lnboundDate);
                            var dateStr = date.getFullYear() + '-' + 
                                         (date.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                                         date.getDate().toString().padStart(2, '0');
                            $('#lnboundDate').val(dateStr);
                        }
                        
                        // 初始化自动生成开关为关闭状态
                        $('input[name="AutoGenerate"]').prop('checked', false);
                        $('#lnboundCodeInput').prop('readonly', false).removeClass('disabled');
                        form.render();
                        
                    } else {
                        layer.msg('加载数据失败：' + result.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.close(loading);
                    layer.msg('加载数据失败', {icon: 2});
                }
            });
        }

        // 表单提交
        form.on('submit(procurementSubmit)', function(data){
            // 手动收集所有字段的值，确保包含只读字段
            var formData = {
                Id: procurementId,
                LnboundCode: $('#lnboundCodeInput').val(),
                LnboundName: $('input[name="LnboundName"]').val(),
                LnboundDate: $('input[name="LnboundDate"]').val(),
                ProcurementNumber: $('input[name="ProcurementNumber"]').val(),
                Vendor: $('input[name="Vendor"]').val(),
                LnboundWarehouse: $('select[name="LnboundWarehouse"]').val(),
                DocumentStatus: $('select[name="DocumentStatus"]').val(),
                TotalAmount: $('input[name="TotalAmount"]').val(),
                Pemark: $('textarea[name="Pemark"]').val(),
                SupplierId: $('#supplierId').val()
            };
            
            // 调试信息
            console.log('=== 修改表单数据收集 ===');
            console.log('ID:', formData.Id);
            console.log('入库单编号:', formData.LnboundCode);
            console.log('入库单名称:', formData.LnboundName);
            console.log('入库日期:', formData.LnboundDate);
            console.log('采购订单号:', formData.ProcurementNumber);
            console.log('供应商:', formData.Vendor);
            console.log('入库仓库:', formData.LnboundWarehouse);
            console.log('单据状态:', formData.DocumentStatus);
            console.log('总金额:', formData.TotalAmount);
            console.log('备注:', formData.Pemark);
            console.log('完整表单数据:', formData);
            
            // 前端验证
            if (!validateForm(formData)) {
                return false;
            }
            
            var loading = layer.load(2, {
                content: '正在提交...',
                time: 10*1000
            });
            
            // 转换日期格式
            if (formData.LnboundDate) {
                formData.LnboundDate = new Date(formData.LnboundDate).toISOString();
            }
            
            // 转换数字类型
            formData.DocumentStatus = parseInt(formData.DocumentStatus);
            
            // 发送修改请求
            $.ajax({
                url: '/WarehouseManagement/UpdateProcurement',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(result) {
                    layer.close(loading);
                    if (result.success) {
                        layer.msg('修改成功', {
                            icon: 1,
                            time: 2000
                        }, function() {
                            window.location.href = '/WarehouseManagement/ProcurementView';
                        });
                    } else {
                        layer.msg('修改失败：' + result.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.close(loading);
                    layer.msg('修改失败', {icon: 2});
                }
            });
            
            return false; // 阻止表单跳转
        });

        // 供应商选择按钮
        $('#selectSupplierBtn').on('click', function() {
            openSupplierSelectDialog();
        });

        // 打开供应商选择对话框
        function openSupplierSelectDialog() {
            var supplierDialog = layer.open({
                type: 1,
                title: '供应商选择',
                area: ['1000px', '600px'],
                maxmin: true,
                content: `
                    <div style="padding: 20px;">
                        <!-- 搜索表单 -->
                        <form class="layui-form" lay-filter="supplierSearchForm" style="margin-bottom: 20px;">
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">供应商编码</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="supplierCode" placeholder="请输入供应商编码" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">供应商名称</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="supplierName" placeholder="请输入供应商名称" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button type="button" class="layui-btn" id="supplierSearchBtn">
                                        <i class="layui-icon layui-icon-search"></i> 搜索
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-primary" id="supplierResetBtn">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                </div>
                            </div>
                        </form>
                        
                        <!-- 供应商列表表格 -->
                        <table class="layui-hide" id="supplierTable" lay-filter="supplierTable"></table>
                        
                        <!-- 操作按钮 -->
                        <div style="text-align: center; margin-top: 20px;">
                            <button type="button" class="layui-btn" id="confirmSelectBtn">确定</button>
                            <button type="button" class="layui-btn layui-btn-primary" id="cancelSelectBtn">取消</button>
                        </div>
                    </div>
                `,
                success: function(layero, index) {
                    // 初始化供应商表格
                    initSupplierTable();
                    
                    // 绑定搜索按钮事件
                    $('#supplierSearchBtn').on('click', function() {
                        loadSupplierData();
                    });
                    
                    // 绑定重置按钮事件
                    $('#supplierResetBtn').on('click', function() {
                        $('input[name="supplierCode"]').val('');
                        $('input[name="supplierName"]').val('');
                        loadSupplierData();
                    });
                    
                    // 绑定确定按钮事件
                    $('#confirmSelectBtn').on('click', function() {
                        var checkStatus = layui.table.checkStatus('supplierTable');
                        if (checkStatus.data.length === 0) {
                            layer.msg('请选择一个供应商', {icon: 2});
                            return;
                        }
                        if (checkStatus.data.length > 1) {
                            layer.msg('只能选择一个供应商', {icon: 2});
                            return;
                        }
                        
                        var selectedSupplier = checkStatus.data[0];
                        $('input[name="Vendor"]').val(selectedSupplier.supplierName);
                        $('#supplierId').val(selectedSupplier.id);
                        
                        layer.close(index);
                        layer.msg('供应商选择成功', {icon: 1});
                    });
                    
                    // 绑定取消按钮事件
                    $('#cancelSelectBtn').on('click', function() {
                        layer.close(index);
                    });
                }
            });
        }

        // 初始化供应商表格
        function initSupplierTable() {
            layui.table.render({
                elem: '#supplierTable',
                url: '/ProductionSystem/SupplierModel/GetSupplierList',
                method: 'GET',
                page: true,
                limit: 10,
                limits: [10, 20, 50],
                cols: [[
                    {type: 'radio', fixed: 'left'},
                    {field: 'supplierCode', title: '供应商编码', width: 120},
                    {field: 'supplierName', title: '供应商名称', width: 150},
                    {field: 'supplierGrade', title: '供应商等级', width: 120},
                    {field: 'supplierPhone', title: '供应商电话', width: 130},
                    {field: 'isEnable', title: '是否启用', width: 100, templet: function(d) {
                        return d.isEnable ? '<span style="color: #1890ff;">是</span>' : '<span style="color: #999;">否</span>';
                    }}
                ]],
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },
                where: {
                    supplierCode: '',
                    supplierName: ''
                }
            });
        }

        // 加载供应商数据
        function loadSupplierData() {
            var supplierCode = $('input[name="supplierCode"]').val();
            var supplierName = $('input[name="supplierName"]').val();
            
            layui.table.reload('supplierTable', {
                where: {
                    supplierCode: supplierCode,
                    supplierName: supplierName
                },
                page: {
                    curr: 1
                }
            });
        }

        // 取消按钮
        $('#cancelBtn').on('click', function() {
            layer.confirm('确认要取消吗？未保存的修改将丢失', {
                icon: 3,
                title: '确认操作'
            }, function(index) {
                window.location.href = '/WarehouseManagement/ProcurementView';
                layer.close(index);
            });
        });

        // 获取url参数id
        function getQueryString(name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return decodeURIComponent(r[2]);
            return null;
        }
        var inboundId = getQueryString('id');

        // 渲染物料明细表格
        function renderMaterialDetailsTable() {
            var lnboundCode = $('#lnboundCodeInput').val() || inboundId;
            table.render({
                elem: '#materialDetailsTable',
                url: '/WarehouseManagement/QueryMaterialReceiptLine',
                method: 'post',
                contentType: 'application/json',
                where: JSON.stringify({
                    LnboundCode: lnboundCode,
                    page: 1,
                    limit: 10
                }),
                page: true,
                limit: 10,
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'materialCode', title: '物料编码'},
                    {field: 'materialName', title: '物料名称'},
                    {field: 'documentAmount', title: '单据金额'},
                    {field: 'unit', title: '单位'},
                    {field: 'receiptQuantity', title: '入库数量'},
                    {field: 'receiptBatchNo', title: '入库批次号'},
                    {field: 'receiptWarehouse', title: '入库仓库'},
                    {field: 'expiryDate', title: '有效期'},
                    {field: 'whethertoInspect', title: '是否检验'},
                    {field: 'remarks', title: '备注'},
                    {title: '操作', toolbar: '#materialDetailOperationBar', width: 100, fixed: 'right'}
                ]],
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },
                parseData: function(res){
                    return {
                        code: res.code,
                        msg: res.msg,
                        count: res.count,
                        data: res.data
                    };
                }
            });
        }
        renderMaterialDetailsTable();

        // 新增明细
        $('#btnAddMaterialDetail').off('click').on('click', function(){
            var inboundId = getQueryString('id');
            layer.open({
                type: 1,
                title: false,
                area: ['900px', '520px'],
                content: $('#addMaterialDetailDialog').html(),
                success: function(layero, index){
                    var formElem = layero.find('form');
                    layui.form.render();
                    // 设置标题
                    layero.find('#materialDetailDialogTitle').text('添加物料入库单行');
                    // 回显入库单编号
                    formElem.find('input[name="InboundId"]').val(inboundId);
                    // 数量加减
                    var qtyInput = formElem.find('input[name="Quantity"]');
                    formElem.find('#btnMinusQty').on('click', function(){
                        var v = parseInt(qtyInput.val()) || 0;
                        if(v > 0) qtyInput.val(v-1);
                    });
                    formElem.find('#btnAddQty').on('click', function(){
                        var v = parseInt(qtyInput.val()) || 0;
                        qtyInput.val(v+1);
                    });
                    // 金额加减
                    var amountInput = formElem.find('input[name="Amount"]');
                    formElem.find('#btnMinusAmount').on('click', function(){
                        var v = parseFloat(amountInput.val()) || 0;
                        if(v > 0) amountInput.val(v-1);
                    });
                    formElem.find('#btnAddAmount').on('click', function(){
                        var v = parseFloat(amountInput.val()) || 0;
                        amountInput.val(v+1);
                    });
                    // 有效期日期选择
                    layui.laydate.render({
                        elem: formElem.find('#validDateInput')[0],
                        type: 'date'
                    });
                    // 入库仓库下拉（写死三条数据）
                    formElem.find('#warehouseSelect').html('<option value="">请选择</option>' +
                        '<option value="WH001">原料仓库</option>' +
                        '<option value="WH002">成品仓库</option>' +
                        '<option value="WH003">半成品仓库</option>');
                    layui.form.render('select');
                    // 物料选择弹窗
                    formElem.find('#btnSelectMaterial').on('click', function(){
                        layer.open({
                            type: 1,
                            title: '选择物料',
                            area: ['900px', '600px'],
                            content: $('#materialSelectDialog').html(),
                            success: function(matLayero, matIndex){
                                layui.table.render({
                                    elem: matLayero.find('#materialTable'),
                                    url: '/ProductionSystem/MasterData/QueryMateriel',
                                    method: 'get',
                                    where: {
                                        materielCode: '',
                                        materielName: '',
                                        PageIndex: 1,
                                        PageSize: 10
                                    },
                                    page: true,
                                    limit: 10,
                                    request: {
                                        pageName: 'PageIndex',
                                        limitName: 'PageSize'
                                    },
                                    cols: [[
                                        {type: 'radio', fixed: 'left'},
                                        {field: 'materielCode', title: '物料编码'},
                                        {field: 'materielName', title: '物料名称'},
                                        {field: 'specifications', title: '规格型号'},
                                        {field: 'unitsId', title: '单位'}
                                    ]],
                                    parseData: function(res){
                                        return {
                                            code: res.code,
                                            msg: res.msg,
                                            count: res.count,
                                            data: res.data
                                        };
                                    }
                                });
                                layui.form.on('submit(materialSearch)', function(data){
                                    layui.table.reload('materialTable', {
                                        where: Object.assign({}, data.field, { PageIndex: 1, PageSize: 10 })
                                    });
                                    return false;
                                });
                                matLayero.find('#materialSelectOk').on('click', function(){
                                    var checked = layui.table.checkStatus('materialTable').data[0];
                                    if(!checked){
                                        layer.msg('请选择物料');
                                        return;
                                    }
                                    formElem.find('input[name="MaterialCode"]').val(checked.materielCode);
                                    formElem.find('input[name="MaterialName"]').val(checked.materielName);
                                    formElem.find('input[name="Unit"]').val(checked.unitsId);
                                    formElem.find('input[name="Specification"]').val(checked.specifications);
                                    layer.close(matIndex);
                                });
                            }
                        });
                    });
                },
                yes: function(index, layero){
                    var formElem = layero.find('form');
                    var data = {};
                    formElem.serializeArray().forEach(function(item){ data[item.name] = item.value; });
                    // 校验逻辑：入库数量和金额必须大于0，其它字段非空
                    if(!data.MaterialCode){ layer.msg('请选择物料编码'); return; }
                    if(!data.MaterialName){ layer.msg('物料名称不能为空'); return; }
                    if(!data.Unit){ layer.msg('单位不能为空'); return; }
                    if(!data.Quantity || isNaN(data.Quantity) || parseInt(data.Quantity) <= 0){ layer.msg('入库数量必须大于0'); return; }
                    if(!data.Amount || isNaN(data.Amount) || parseFloat(data.Amount) <= 0){ layer.msg('单据金额必须大于0'); return; }
                    if(!data.Warehouse){ layer.msg('请选择入库仓库'); return; }
                    if(!data.Specification){ layer.msg('规格型号不能为空'); return; }
                    if(!data.BatchNo){ layer.msg('入库批次号不能为空'); return; }
                    if(!data.ValidDate){ layer.msg('有效期不能为空'); return; }
                    if(!data.Remark){ layer.msg('备注不能为空'); return; }
                    $.ajax({
                        url: '/WarehouseManagement/CreateMaterialReceiptLine',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            LnboundCode: $('#lnboundCodeInput').val(),
                            MaterialCode: data.MaterialCode,
                            MaterialName: data.MaterialName,
                            Unit: data.Unit,
                            ReceiptQuantity: parseInt(data.Quantity),
                            DocumentAmount: parseFloat(data.Amount),
                            ReceiptWarehouse: data.Warehouse,
                            ReceiptBatchNo: data.BatchNo,
                            ExpiryDate: data.ValidDate,
                            WhethertoInspect: data.IsCheck,
                            Remarks: data.Remark
                        }),
                        success: function(res){
                            if(res.success){
                                layer.msg('新增成功', {icon:1});
                                layer.close(index);
                                renderMaterialDetailsTable();
                            }else{
                                layer.msg('新增失败：'+res.message, {icon:2});
                            }
                        },
                        error: function(){
                            layer.msg('请求失败', {icon:2});
                        }
                    });
                }
            });
        });

        // 批量删除明细
        $('#btnDeleteMaterialDetail').on('click', function(){
            var checkStatus = table.checkStatus('materialDetailsTable');
            var selected = checkStatus.data;
            if(selected.length === 0){
                layer.msg('请先选择要删除的明细', {icon:2});
                return;
            }
            layer.confirm('确认删除选中的明细吗？', {icon:3, title:'提示'}, function(idx){
                var ids = selected.map(function(item){ return item.id; });
                $.ajax({
                    url: '/WarehouseManagement/DeleteMaterialReceiptLine',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(ids),
                    success: function(res){
                        if(res.success){
                            layer.msg('删除成功', {icon:1});
                            renderMaterialDetailsTable();
                        }else{
                            layer.msg('删除失败：'+res.message, {icon:2});
                        }
                    },
                    error: function(){
                        layer.msg('请求失败', {icon:2});
                    }
                });
                layer.close(idx);
            });
        });

        // 行内编辑/删除
        table.on('tool(materialDetailsTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                layer.open({
                    type: 1,
                    title: false,
                    area: ['700px', '520px'],
                    content: $('#addMaterialDetailDialog').html(),
                    success: function(layero, index){
                        // 设置标题
                        layero.find('#materialDetailDialogTitle').text('编辑物料明细');
                        // 回显数据
                        form.val('addMaterialDetailForm', {
                            MaterialCode: data.materialCode,
                            MaterialName: data.materialName,
                            Amount: data.documentAmount,
                            Specification: data.specification,
                            Unit: data.unit,
                            Quantity: data.receiptQuantity,
                            BatchNo: data.receiptBatchNo,
                            Warehouse: data.receiptWarehouse,
                            ValidDate: data.expiryDate,
                            IsCheck: data.whethertoInspect,
                            Remark: data.remarks,
                            InboundId: inboundId,
                            Id: data.id
                        });
                        layui.form.render();
                    }
                });
            }else if(obj.event === 'delete'){
                layer.confirm('确认删除该明细吗？', {icon:3, title:'提示'}, function(idx){
                    $.ajax({
                        url: '/WarehouseManagement/DeleteMaterialReceiptLine',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify([data.id]),
                        success: function(res){
                            if(res.success){
                                layer.msg('删除成功', {icon:1});
                                renderMaterialDetailsTable();
                            }else{
                                layer.msg('删除失败：'+res.message, {icon:2});
                            }
                        },
                        error: function(){
                            layer.msg('请求失败', {icon:2});
                        }
                    });
                    layer.close(idx);
                });
            }
        });
    });
    </script>
</body>
</html>
